<template>
  <el-select v-model="sval" clearable placeholder="请选择事项" :style="{width}" class="small-el-input__inner" popper-class="samll-el-select-dropdown__list" @change="onChcange">
    <el-option v-for="dt in lists" :key="dt.stageTaskId" :value="dt.stageTaskId" :label="dt.taskName" />
  </el-select>
</template>
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { getTaskList } from '@/api/plant'
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()

const props = defineProps({
  modelValue: '',
  width: {
    type: String,
    default: '100%'
  },
  params: { // 查询条件
    type: Object,
    default: {}
  },
  keyName: '' // 返回的属性名对应的值
})
const emit = defineEmits(['update:modelValue', 'change'])
const sval = ref('')
const lists = ref('')

onMounted(() => {
  getTableData()
})

watch(() => props.modelValue, (n, o) => {
  sval.value = n
})

const getTableData = async() => {
  const res = await getTaskList({ page: 1, limit: 1000000, farmId: userStore.userInfo.farmId, ...props.params })
  if (res.success) {
    lists.value = res.data
    sval.value = props.modelValue || '' // 设置默认选项
 }
}

const onChcange = () => {
  if (props.keyName) {
    const item = lists.value.find(ele => ele.id === sval.value)
    emit('update:modelValue', item[props.keyName])
    emit('change', sval.value)
    emit('changeName', sval.value)
  } else {
    emit('update:modelValue', sval.value)
    emit('change', sval.value)
    const item = lists.value.find(ele => ele.stageTaskId === sval.value)
    emit('changeName', item?.taskName || '')
  }
}
</script>

<style scoped lang="scss">
</style>
